package com.lwl.blog.system.interceptor;


import com.lwl.blog.core.exception.TokenException;
import com.lwl.blog.system.dto.UserToken;
import com.lwl.blog.system.service.impl.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *<p>
 *     登录拦截器
 *</p>
 *
 * @author lwl
 * @since  22-12-26
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,Object handler) throws Exception{

        //1.从请求头获取token
        String token = req.getHeader("token");

        //2.校验token合法性
        if (ObjectUtils.isEmpty(token)){
            throw new TokenException(201,"token为空!");
        }

        UserToken token1 = tokenService.getToken(token);

        if (token1==null){
            throw new TokenException(201, "token有误");
        }
        //放行
        return true;
    }


}
